#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Ka3u6y6a'

import os

from PyQt4 import QtCore, QtGui
from PIL.ImageQt import ImageQt
from engine import cbgetimg



class ImageView(QtGui.QGraphicsView):
    def __init__(self, parent=None, origPixmap=None):
        """
          QGraphicsView that will show an image scaled to the current widget size
          using events
          """
        super(ImageView, self).__init__(parent)
        self.origPixmap = origPixmap
        QtCore.QMetaObject.connectSlotsByName(self)

    def resizeEvent(self, event):
        """
          Handle the resize event.
          """
        size = event.size()
        item =  self.items()[0]

        # using current pixmap after n-resizes would get really blurry image
        #pixmap = item.pixmap()
        pixmap = self.origPixmap

        #pixmap = pixmap.scaled(size, QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)
        #self.centerOn(1.0, 1.0)
        item.setPixmap(pixmap)
        item.setOpacity(0.1)

class ViewDiffWindow(QtGui.QWidget):
    def __init__(self, *args):
        QtGui.QWidget.__init__(self, *args)


        # buttons
        #spacer = QtGui.QSpacerItem(20,40,QtGui.QSizePolicy.Minimum,QtGui.QSizePolicy.Expanding)
        self.button_next = QtGui.QPushButton()
        self.button_next.setText(u"Дальше >>")
        self.button_next.setDefault(True)
        self.button_prev = QtGui.QPushButton()
        self.button_prev.setText(u"<< Назад")
        button_cancel = QtGui.QPushButton()
        button_cancel.setText(u"Выход")
        self.cbMask = QtGui.QCheckBox(u'Наложить различия', self)


        self.imageB = QtGui.QLabel(self) #QtGui.QScrollArea(self)
        #self.imageB.setSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)
        self.imageB.setScaledContents(True)
        self.imageB.setPixmap(QtGui.QPixmap(cbgetimg.img1))

        scrollArea = QtGui.QScrollArea()
        scrollArea.setBackgroundRole(QtGui.QPalette.Dark)
        scrollArea.setWidget(self.imageB)

        self.imageD = QtGui.QLabel(self) #QtGui.QScrollArea(self)
        #self.imageB.setSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored)
        self.imageD.setScaledContents(True)
        self.imageD.setPixmap(QtGui.QPixmap(cbgetimg.img3))
        self.imageD.setAttribute(QtCore.Qt.WA_NoSystemBackground)
        self.imageD.setAttribute(QtCore.Qt.WA_TranslucentBackground)


        self.scrollAreaD = QtGui.QScrollArea()
        #scrollAreaD.setBackgroundRole(QtGui.QPalette.Dark)
        self.scrollAreaD.setWidget(self.imageD)
        self.scrollAreaD.setAttribute(QtCore.Qt.WA_NoSystemBackground)
        self.scrollAreaD.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.scrollAreaD.hide()


        # layout
        layout_right = QtGui.QGridLayout(self)
        layout_right.addWidget(scrollArea,0,0,10,10)
        layout_right.addWidget(self.scrollAreaD,0,0,10,10) #
        #layout_right.addItem(spacer)
        layout_right.addWidget(self.button_prev,11,8,1,1)
        layout_right.addWidget(self.button_next,11,9,1,1)
        layout_right.addWidget(self.cbMask,11,7,1,1)
        layout_right.addWidget(button_cancel,11,0,1,1)

        self.setWindowTitle("CBV :: Image Preview")
        self.setMinimumSize(800,800)
        self.resize(800, 800)

        # connections
        self.connect(button_cancel, QtCore.SIGNAL("clicked(bool)"), self.closeClicked)
        self.connect(self.cbMask, QtCore.SIGNAL("stateChanged(int)"), self.diffImage)
        self.connect(self.button_next, QtCore.SIGNAL("clicked(bool)"), self.nextClicked)

    def nextClicked(self):

        self.imageB.setPixmap(QtGui.QPixmap(cbgetimg.img2))
        #self.imageB.baseSize()
        print 'next'

    def closeClicked(self):
        self.close()
        print 'close'

    def diffImage(self, i = None):
        if i == 2:
            print 'checkBox - 2'
            pilimage = cbgetimg.compareImages(cbgetimg.img1, cbgetimg.img2)

            imageq = ImageQt(pilimage) #convert PIL image to a PIL.ImageQt object
            qimage = QtGui.QImage(imageq) #cast PIL.ImageQt object to QImage object -that´s the trick!!!

            self.imageD.setPixmap(QtGui.QPixmap(qimage))
            self.scrollAreaD.show()

        elif i == 0:
            print 'checkBox - 0'
            #self.imageD.hide()
            self.scrollAreaD.hide()

        else:
            print 'checkBox - None'


class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.createActions()
        self.createMenus()
        self.createStatusBar()
        self.createTrayIcon()
        self.createMainWidget()
        # create progress bar
        self.pb = QtGui.QProgressBar(self.statusBar())
        self.statusBar().addPermanentWidget(self.pb)
        self.pb.setRange(0, 100)
        self.pb.setValue(0)
        self.pb.hide()

        #Добавляем виджет
        self.setCentralWidget(self.mainWindowControls)

        icon = QtGui.QIcon('/images/bad.svg')
        self.trayIcon.setIcon(icon)
        self.setWindowIcon(icon)		
        self.trayIcon.show()		
        self.setWindowTitle("CB Viewer")
        self.setMinimumSize(160,160)
        self.resize(400, 300)
          
        
    def about(self):
        QtGui.QMessageBox.about(self, "About Application",
                "The <b>Application</b> example demonstrates how to write "
                "modern GUI applications using Qt, with a menu bar, "
                "toolbars, and a status bar.")
				
    def createActions(self):
        self.newAct = QtGui.QAction(QtGui.QIcon('/images/bad.svg'), "&New",
                self, shortcut=QtGui.QKeySequence.New, statusTip="Create a new file", triggered=self.about)

        self.exitAct = QtGui.QAction("E&xit", self, shortcut="Ctrl+Q", statusTip="Exit the application", triggered=self.close)
        #Выход номер один
        self.cutAct = QtGui.QAction(QtGui.QIcon('/images/bad.svg'), "Cu&t",
                self, shortcut=QtGui.QKeySequence.Cut, statusTip="Cut the current selection's contents to the clipboard", triggered=self.about)

        self.aboutAct = QtGui.QAction("&About", self, statusTip="Show the application's About box", triggered=self.about)
        self.aboutQtAct = QtGui.QAction("About &Qt", self,  statusTip="Show the Qt library's About box", triggered=QtGui.qApp.aboutQt)

        self.minimizeAction = QtGui.QAction("Mi&nimize", self, triggered=self.hide)
        self.maximizeAction = QtGui.QAction("Ma&ximize", self, triggered=self.showMaximized)
        self.restoreAction = QtGui.QAction("&Restore", self, triggered=self.showNormal)
        #Выход номер два
        self.quitAction = QtGui.QAction("&Quit", self, triggered=QtGui.qApp.quit)


    def createMenus(self):
        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenu.addAction(self.newAct)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.exitAct)

        self.editMenu = self.menuBar().addMenu("&Edit")
        self.editMenu.addAction(self.cutAct)

        self.menuBar().addSeparator()

        self.helpMenu = self.menuBar().addMenu("&Help")
        self.helpMenu.addAction(self.aboutAct)
        self.helpMenu.addAction(self.aboutQtAct)
		
		
    def createStatusBar(self, message=None, time=5000):
        #self.sb = QtGui.QStatusBar()
        #self.sb.setFixedHeight(18)
        #self.setStatusBar(self.sb)
        if message == None: self.statusBar().showMessage("Ready", time)
        else: self.statusBar().showMessage(message, time)
		
    def createTrayIcon(self):
         self.trayIconMenu = QtGui.QMenu(self)
         self.trayIconMenu.addAction(self.minimizeAction)
         self.trayIconMenu.addAction(self.maximizeAction)
         self.trayIconMenu.addAction(self.restoreAction)
         self.trayIconMenu.addSeparator()
         self.trayIconMenu.addAction(self.quitAction)

         self.trayIcon = QtGui.QSystemTrayIcon(self)
         self.trayIcon.setContextMenu(self.trayIconMenu)

    def createMainWidget(self):
        self.mainWindowControls = QtGui.QWidget()

        ###ГрупБокс ПРОЕКТЫ
        self.projGroupBox = QtGui.QGroupBox(u" Проекты ")
        self.projLabel = QtGui.QLabel(u"Список проектов:")
        projLayout = QtGui.QHBoxLayout()
        projLayout.addWidget(self.projLabel)
        self.projGroupBox.setLayout(projLayout)
        ###ГрупБокс ПРОЕКТЫ конец

        ###ГрупБокс НОВЫЕ ПРОЕКТЫ
        self.newprojGroupBox = QtGui.QGroupBox(u" Новый проект ")
        self.nameBrowsers = QtGui.QLabel(u"Браузеры")
        self.cbIE = QtGui.QCheckBox('IE-9', self)
        self.cbFF = QtGui.QCheckBox('FireFox', self)
        self.cbCH = QtGui.QCheckBox('Chrome', self)
        self.nameUrlLabel = QtGui.QLabel(u"URL сайта")
        self.urlEditor = QtGui.QLineEdit()
        self.urlEditor.setText(u"http://")
        self.nameProjLabel = QtGui.QLabel(u"Имя проекта")
        self.projNameEditor = QtGui.QLineEdit()
        self.projNameEditor.setText(u"Новый проект")
        ###ГрупБокс НОВЫЕ ПРОЕКТЫ конец

        pLayout = QtGui.QGridLayout()
        pLayout.addWidget(self.nameBrowsers, 0, 0, 1, 1)
        pLayout.addWidget(self.cbIE, 0, 1, 1, 1)
        pLayout.addWidget(self.cbFF, 0, 2, 1, 1)
        pLayout.addWidget(self.cbCH, 0, 3, 1, 1)
        pLayout.addWidget(self.nameProjLabel, 1, 0, 1, 3)
        pLayout.addWidget(self.projNameEditor, 1, 1, 1, 3)
        pLayout.addWidget(self.nameUrlLabel, 2, 0, 1, 3)
        pLayout.addWidget(self.urlEditor, 2, 1, 1, 3)
        self.newprojGroupBox.setLayout(pLayout)

        self.startButton = QtGui.QPushButton(u"Старт!")

        ###Общий вывод окна
        layout = QtGui.QGridLayout()
        layout.addWidget(self.projGroupBox)
        layout.addWidget(self.newprojGroupBox)
        layout.addWidget(self.startButton)
        self.mainWindowControls.setLayout(layout)

        ###Сигналы
        self.cbIE.stateChanged.connect(lambda: self.viewDiff())
        self.cbFF.stateChanged.connect(lambda: self.createStatusBar('FireFox'))
        self.cbCH.stateChanged.connect(lambda: self.createStatusBar('Chrome'))
        #self.startButton.clicked.connect(lambda: cbgetimg.testBrowser(str(self.urlEditor.text())))
        self.startButton.clicked.connect(lambda: self.startSelenium())

    def startSelenium(self):
        if str(self.urlEditor.text()) == 'http://':
            self.createStatusBar(u'Вы не ввели URL')
            return
        self.newprojGroupBox.setDisabled(True)
        self.pb.show()
        ###IE-9
        self.pb.setValue(5)
        if self.cbIE.checkState() == 2:
            print 'IE'
            self.pb.setValue(15)
            self.createStatusBar(u'Получение данных из IE-9...')

        ###FireFox
        self.pb.setValue(30)
        if self.cbFF.checkState() == 2:
            print 'FF'
            self.createStatusBar(u'Получение данных из FireFox...')
            self.pb.setValue(35)
            cbgetimg.testBrowser('FF', str(self.urlEditor.text()))
            self.pb.setValue(45)
            self.pb.setValue(55)

        ###Chrome
        self.pb.setValue(60)
        if self.cbCH.checkState() == 2:
            print 'CH'
            self.createStatusBar(u'Получение данных из Chrome...')
            self.pb.setValue(65)
            cbgetimg.testBrowser('CH', str(self.urlEditor.text()))
            self.pb.setValue(75)
            self.pb.setValue(85)

        if self.cbIE.checkState() + self.cbFF.checkState() + self.cbCH.checkState() == 0:
            self.pb.setValue(100)
            self.createStatusBar(u'Не выбран ни один браузер')
            self.newprojGroupBox.setDisabled(False)
            return

        self.pb.setValue(90)
        self.createStatusBar(u'Сверяю данные...')
        cbgetimg.compareImages(cbgetimg.img1, cbgetimg.img2)

        from PIL import Image
        im = Image.open(cbgetimg.img3)
        im.show()

        self.pb.setValue(100)
        self.createStatusBar(u'Готово!')
        self.newprojGroupBox.setDisabled(False)
        #cbgetimg.testBrowser(str(self.urlEditor.text()))

    def viewDiff(self):
        self.hide()
        self.vdWindow = ViewDiffWindow()
        self.vdWindow.show()
        print 1



if __name__ == '__main__':

    import sys

    
    app = QtGui.QApplication(sys.argv)

    app.setStyle("Plastique")
    #app.setStyleSheet(open("D:\\Home\\tmp\\py\\Chat\\systray\\systray.qss","r").read())

    if not QtGui.QSystemTrayIcon.isSystemTrayAvailable():
        QtGui.QMessageBox.critical(None, "Systray", "I couldn't detect any system tray on this system.")
        sys.exit(1)

    #Для сворачивания в трей при закрытии
    QtGui.QApplication.setQuitOnLastWindowClosed(False)

    mainWin = MainWindow()
    mainWin.show()
    sys.exit(app.exec_())
